from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse

from common.models import UserProfile, UserAuth, Facility, Area, House
from house_app.models import HouseImage
from my_app.forms import UserProfileForm, AuthForm, NewHouseForm
from user_app.models import Order


def profile(request):
    if request.method == 'GET':
        return render(request, 'profile.html')
    if request.method == 'POST':
        form = UserProfileForm(request.POST, request.FILES)
        # TODO:这里做上传和提交两个表单信息，防止file类型的input没有默认值，暂时解决
        if form.is_valid():
            # 判断是否是对已有的个人信息进行修改，如果是，就可以在没修改姓名的情况下不报错
            user_profile = UserProfile.objects.filter(name=form.cleaned_data.get('name')).first()
            if user_profile:
                # 判断是否和非当前用户的用户名重复
                if (not request.user.user_profile) or (request.user.user_profile != user_profile):
                    error = '该用户名已被使用'
                    return render(request, 'profile.html', {'error': error})
                # 如果是当前用户的用户名，那就是更改信息(准确说是更改头像)
                if request.user.user_profile == user_profile:
                    if form.cleaned_data.get('avatar'):
                        request.user.user_profile.avatar = form.cleaned_data.get('avatar')
                        request.user.user_profile.save()
                    return HttpResponseRedirect(reverse('user:my'))
            # 下面三行代码确定当前用户可不可以修改用户名
            if request.user.user_profile:
                error = '用户名不可更改！'
                return render(request, 'profile.html', {'error': error})
            # 添加并保存user_profile对象
            user_profile = UserProfile.objects.create(name=form.cleaned_data.get('name'),
                                                      avatar=form.cleaned_data.get('avatar'))
            # 第一次添加个人信息或者修改个人信息(用户名)
            request.user.user_profile = user_profile
            request.user.save()
            return HttpResponseRedirect(reverse('user:my'))
        errors = form.errors
        return render(request, 'profile.html', {'errors': errors})


def orders(request):
    if request.method == 'GET':
        orders = request.user.order_set.all()
        return render(request, 'orders.html', {'orders': orders})
    if request.method == 'POST':
        order_id = request.POST.get('order_id')
        comment = request.POST.get('comment')
        order = Order.objects.filter(id=str(order_id)).first()
        order.comment = comment
        order.status = "COMPLETE"
        order.save()
        return HttpResponseRedirect(reverse('my:orders'))


def auth(request):
    if request.method == 'GET':
        return render(request, 'auth.html')
    if request.method == 'POST':
        if request.user.user_auth:
            error = '认证信息不可更改！'
            return render(request, 'auth.html', {'error': error})
        form = AuthForm(request.POST, request.FILES)
        if form.is_valid():
            try:
                user_auth = UserAuth.objects.create(id_name=form.cleaned_data.get('real_name'),
                                                    id_card=form.cleaned_data.get('id_card'))
            except:
                error = '该身份证号码已认证'
                return render(request, 'auth.html', {'error': error})
            request.user.user_auth = user_auth
            request.user.save()
        errors = form.errors
        return render(request, 'auth.html', {'errors': errors})


def my_house(request):
    if request.method == 'GET':
        houses = request.user.house_set.all()
        return render(request, 'my_house.html', {'houses': houses})


def lorders(request):
    if request.method == 'GET':
        orders = Order.objects.all()
        orders = [order for order in orders if order.house_order.user_h == request.user]
        return render(request, 'lorders.html', {'orders': orders})
    if request.method == 'POST':
        accept_id = request.POST.get('accept_id')
        reject_id = request.POST.get('reject_id')
        order = Order.objects.filter(id=accept_id if accept_id else reject_id).first()
        if accept_id:
            order.status = "WAIT_PAYMENT"
        if reject_id:
            reject_reason = request.POST.get('reject_reason')
            order.reject_reason = reject_reason
            order.status = "REJECTED"
        order.save()
        return HttpResponseRedirect(reverse('my:lorders'))


def new_house(request):
    if request.method == 'GET':
        facilities = Facility.objects.all()
        areas = Area.objects.all()
        return render(request, 'new_house.html', {'facilities': facilities, 'areas': areas})
    if request.method == 'POST':
        form = NewHouseForm(request.POST, request.FILES)
        if form.is_valid():
            house = House.objects.create(title=form.cleaned_data['title'],
                                         price=form.cleaned_data['price'],
                                         address=form.cleaned_data['address'],
                                         room_count=form.cleaned_data['room_count'],
                                         acreage=form.cleaned_data['acreage'],
                                         unit=form.cleaned_data['unit'],
                                         capacity=form.cleaned_data['capacity'],
                                         beds=form.cleaned_data['beds'],
                                         deposit=form.cleaned_data['deposit'],
                                         min_days=form.cleaned_data['min_days'],
                                         max_days=form.cleaned_data['max_days'],
                                         )
            # 将该house添加给当前用户
            house.area_h_id = form.cleaned_data['area_id']
            house.user_h = request.user
            # 给该house添加相应设施
            for f in request.POST.getlist('facility'):
                house.facility.add(f)
            house.save()
            # 给该house添加图片
            house_image = HouseImage.objects.create(url=form.cleaned_data['house_image'])
            house.house_image.add(house_image)
            house.index_image_url = house_image.url
            house.save()
            return HttpResponseRedirect(reverse('my:my_house'))
        errors = form.errors
        return HttpResponseRedirect(reverse('my:new_house'), {'errors': errors})


# 这里的房间信息是通过'我的爱家'页面进入的，所以只应该有自己的房间信息
def detail(request, id):
    if request.method == 'GET':
        house = House.objects.filter(pk=id).first()
        return render(request, 'detail.html', {'house': house})



